<template>
  <el-popover ref="popover" trigger="click" placement="bottom-start" width="200">
    <el-tree
      :props="props"
      :data="treeData"
      node-key="id"
      ref="tree"
      accordion
      :default-expand-all="false"
      :expand-on-click-node="false"
      @node-click="onClickNode">
    </el-tree>
    <el-input slot="reference" v-model="labelModel" clearable></el-input>
  </el-popover>
</template>

<script>
  import {mapState} from 'vuex'
  export default {
    name: 'folderSelectTree',
    data () {
      return {
        labelModel: '',
        props: {
          label: 'label',
          children: 'children'
        }
      }
    },
    props: {
      treeData: {
        type: Array,
        default: function () {
          return []
        }
      },
      clear: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      clear: function (val) {
        // setDefaultVal ()
      },
      getFolderPath (val) {
        this.labelModel = val
      }
    },
    computed: {
      getFolderPath () {
        return this.$store.state.folder.folderPath
      }
    },
    mounted () {
      this.setDefaultVal()
    },
    methods: {
      onClickNode (node) {
        this.labelModel = this.getParentFolder(this.$refs.tree.getNode(node.id))
        this.$emit('onClickNode', this.labelModel, node.id)
        this.onCloseTree()
      },
      getParentFolder (node) {
        let level = node.level
        let path = ''
        while (level >= 1) {
          path = '/' + node.data.label + path
          node = node.parent
          level--
        }
        return path
      },
      onCloseTree () {
        this.$refs.popover.showPopper = false
      },
      setDefaultVal () {
        let path = '/'
        let value = this.$store.state.folder.currentPath.paths
        value.forEach(v => {
          path += v + '/'
        })
        this.labelModel = path.substring(0, path.length - 1)
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
